package com.iussoft.receive.controller;

import com.alibaba.fastjson.JSON;
import com.apache.api.api.ApiService;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.rpc.common.JsonEntityParese;
import com.apache.rpc.common.XMLMapParse;
import com.apache.tools.StrUtil;
import com.iussoft.tools.AesUtil;
import com.iussoft.tools.LoggerUtil;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * description: restful请求接口
 */
@Controller
public class ReceiveServiceAction {

	@Autowired
	private ApiService receiveService;

	/**
	 * description:  系统统一内部接口(restfull--post)
	 */
	@RequestMapping(value = "/receive/service/doService", method = {RequestMethod.POST,RequestMethod.GET})
	public void doServiceForRf(HttpServletRequest request, HttpServletResponse response) {
		ParamsVo vo = new ParamsVo();
		String reqMsg = null;
		try {
			reqMsg = IOUtils.toString(request.getInputStream(), "UTF-8");//以流的方式传参
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (StrUtil.isNull(reqMsg)) {//xml参数
			String paramStr = request.getParameter("params");
			if (StrUtil.isNotNull(paramStr)) {
				Map<String, Object> headMap = new HashMap<String, Object>();
				Map<String, Object> bodyMap = new HashMap<String, Object>();
				XMLMapParse.instance().xmlGetData(paramStr, headMap, bodyMap);
				vo.setMethodKey(headMap.get("MethodCode").toString());
				vo.setParams(bodyMap);
			} else {
				String methodCode = request.getParameter("MethodCode");
				Map<String, Object> bodyMap = getRequestParam(request);
				vo.setMethodKey(methodCode);
				vo.setParams(bodyMap);
			}
		} else {
			Map<String, Object> headMap = new HashMap<String, Object>();
			Map<String, Object> bodyMap = new HashMap<String, Object>();
			XMLMapParse.instance().xmlGetData(reqMsg, headMap, bodyMap);
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
		}
		String result = "";
		try {
			ResultEntity entity = getResultInfo(vo);
			String callback = request.getParameter("callback");
			PrintWriter out = response.getWriter();
			if (StrUtil.isNull(callback)) {
				String paramType = request.getParameter("ParamType");
				if ("json".equalsIgnoreCase(paramType))
					result = JsonEntityParese.instance().beanToJson(entity);
				else
					result = JsonEntityParese.instance().toXml(entity);
				response.setContentType("text/html; charset=UTF-8");
				out.print(result);
			} else {///支持jsonp数据格式
				response.setContentType("application/javascript");
				if (StrUtil.isEmpty(entity.getEntity())) {
					ResultMsg msg = new ResultMsg("F", "操作失败");
					JSONObject json = JSONObject.fromObject(msg);
					result = json.toString();
				} else {
					JSONObject json = JSONObject.fromObject(entity);
					result = json.toString();
				}
				out.print(callback + "(" + result + ")");
			}
			out.flush();
		} catch (Exception e) {
		}
	}

	/**
	 * description:  系统统一对外接口(restfull--post)
	 */
	@ResponseBody
	@RequestMapping(value = "/receive/api/doInvoke/{sysPass}", method = {RequestMethod.POST})
	public Object doService(HttpServletRequest request, HttpServletResponse response, String beanId, @PathVariable("sysPass") String sysPass) {
		ResultEntity entity = null;
		try {
			String reqMsg = IOUtils.toString(request.getInputStream(),"UTF-8");
			LoggerUtil.info("api request params:"+ reqMsg);
			if(StrUtil.isNotNull(sysPass)) {
				reqMsg = AesUtil.getInstance().decryptEcbMode(reqMsg, sysPass);
			}
			ParamsVo params = JSON.parseObject(reqMsg, ParamsVo.class);
			entity = getResultInfo(params);
		}catch (IOException e){
			entity = new ResultEntity();
			entity.setResult("false");
			entity.setMessage("接口调用失败！");
		}
		String data = AesUtil.getInstance().encryptEcbMode(JSON.toJSONString(entity),sysPass);
		return data;
	}

	private ResultEntity getResultInfo(ParamsVo vo) {
		ResultEntity entity = receiveService.doService(vo);
		if (StrUtil.isEmpty(entity)) {
			entity = new ResultEntity();
			entity.setResult("false");
			entity.setMessage("接口调用失败！");
		}
		return entity;
	}

	private Map<String, Object> getRequestParam(HttpServletRequest request) {
		Map<String, Object> bodyMap = new HashMap<String, Object>();
		Set keSet = request.getParameterMap().entrySet();
		for (Iterator itr = keSet.iterator(); itr.hasNext();) {
			Map.Entry me = (Map.Entry) itr.next();
			String ok = String.valueOf(me.getKey());
			if ("ParamType".equals(ok) || "callback".equals(ok) || "MethodCode".equals(ok))
				continue;
			Object ov = me.getValue();
			String[] value = new String[1];
			if (ov instanceof String[]) {
				value = (String[]) ov;
			} else {
				value[0] = ov.toString();
			}
			if (value.length > 0) {
				bodyMap.put(ok, value[0]);
				request.setAttribute(ok, value[0]);
			}
		}
		return bodyMap;
	}

}
